/**
 * 
 */
package autoUpdater.helper;

import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Scanner;

import autoUpdater.AutoUpdaterMain;

/**
 * @author Christian
 * 
 */
public class OnlineStatus {
	
	/**
	 * 
	 */
	private int fileSize = 0;
	
	/**
	 * 
	 */
	private String onlineVersion = "";
	
	/**
	 * 
	 */
	private String updateText = "";
	
	/**
	 * 
	 */
	private String md5Hash = "";
	
	/**
	 * 
	 */
	private URL aktuelleUpdateUrl = null;
	
	/**
	 * @param updateFile
	 *            Addresse des Updatefiles
	 * @throws Exception
	 *             Alle Exceptions werden weitergeworfen
	 */
	public OnlineStatus(String updateFile, String channelPw) throws IOException {

		URL url = new URL(updateFile + "?pw=" + URLEncoder.encode(channelPw, "UTF-8"));
		int count = 0;
		while (count <= 10
				&& (aktuelleUpdateUrl == null || md5Hash.equals("") || fileSize == 0)) {
			Scanner scanner = new Scanner(url.openStream());
			StringBuilder builder = new StringBuilder();
			while (scanner.hasNext()) {
				String part = scanner.nextLine();
				builder.append(part);
				if (part.startsWith("UpdatePath=")) {
					aktuelleUpdateUrl = new URL(part.substring("UpdatePath=".length(), part.length()));
				}
				if (part.startsWith("MD5=")) {
					md5Hash = part.substring("Md5=".length(), part.length());
				}
				if (part.startsWith("FileSize=")) {
					fileSize = (int) Double.parseDouble(part.substring("FileSize=".length(), part
							.length()));
				}
				if (part.startsWith("UpdateText=")) {
					updateText = part.substring("UpdateText=".length(), part.length());
				}
				if (part.startsWith("Version=")) {
					onlineVersion = part.substring("Version=".length(), part.length());
				}
			}
			scanner.close();
			if (AutoUpdaterMain.isDebugMode()) {
				if (aktuelleUpdateUrl.equals("") || md5Hash.equals("") || fileSize == 0
						|| updateText.equals("")) {
					System.out.println(count);
					System.out.println(builder.toString());
				}
			}
			count++;
			if (count == 10) {
				throw new IOException("Server liefert Müll");
			}
		}
		if (AutoUpdaterMain.isDebugMode()) {
			System.out.println("Laden der Onlinedaten fertig!");
		}
	}
	
	/**
	 * @return the fileSize
	 */
	public int getFileSize() {

		return fileSize;
	}
	
	/**
	 * @return the onlineVersion
	 */
	public String getOnlineVersion() {

		return onlineVersion;
	}
	
	/**
	 * @return the updateText
	 */
	public String getUpdateText() {

		return updateText;
	}
	
	/**
	 * @return the md5Hash
	 */
	public String getMd5Hash() {

		return md5Hash;
	}
	
	public URL getAktuelleUpdateUrl() {

		return aktuelleUpdateUrl;
	}
}
